#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:Zx
@file: announcement.py
@time: 2025/8/19  10:03
# @describe:
"""
import json
import uuid
from datetime import datetime
from pathlib import Path
import os
from flask import current_app


class AnnouncementManager:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self, app=None):
        if not hasattr(self, '_initialized') or not self._initialized:
            self._initialized = True
            self.app = app
            self.data_file = None
            if app is not None:
                self.init_app(app)

    def init_app(self, app):
        """初始化应用，设置数据文件路径"""
        self.app = app
        with app.app_context():
            # 确保data目录存在
            data_dir = os.path.join(current_app.root_path, 'data')
            os.makedirs(data_dir, exist_ok=True)

            # 设置数据文件路径
            self.data_file = os.path.join(data_dir, 'announcements.json')

            # 确保文件存在
            if not os.path.exists(self.data_file):
                with open(self.data_file, 'w', encoding='utf-8') as f:
                    json.dump([], f, ensure_ascii=False, indent=2)

    def _check_initialized(self):
        """检查是否已初始化"""
        if not self.data_file:
            raise RuntimeError("AnnouncementManager 未正确初始化，请先调用 init_app()")

    def _load_data(self):
        """加载公告数据"""
        self._check_initialized()
        try:
            with open(self.data_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except FileNotFoundError:
            return []
        except json.JSONDecodeError:
            return []

    def _save_data(self, data):
        """保存公告数据"""
        if not self.data_file:
            raise RuntimeError("AnnouncementManager 未正确初始化")

        with open(self.data_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

    def get_all(self, limit=5):
        """获取所有公告"""
        data = self._load_data()
        # 按创建时间降序排序并限制数量
        sorted_data = sorted(data, key=lambda x: x['created_at'], reverse=True)
        return sorted_data[:limit]

    def create(self, title, content, user_id):
        """创建新公告"""
        data = self._load_data()
        new_announcement = {
            'id': str(uuid.uuid4()),
            'title': title,
            'content': content,
            'user_id': user_id,
            'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        data.append(new_announcement)
        self._save_data(data)
        print(data)
        return new_announcement

    def delete(self, announcement_id):
        """删除公告"""
        data = self._load_data()
        updated_data = [a for a in data if a['id'] != announcement_id]
        if len(updated_data) == len(data):
            return False  # 没找到要删除的公告
        self._save_data(updated_data)
        return True


# 创建全局实例
announcement_manager = AnnouncementManager()